/*
 * utils.c
 *
 *  Created on: 03-11-2012
 *      Author: Skeith
 */

#include "utils.h"

// Calculate a*x mod m
tU32 mult(unsigned long long a, unsigned long long  x, unsigned long long m)
{
   tU32 b,n,r;

   r = 0;
   n = 1;
   b = 1;
   while (n <= 64)
   {
      if ((a & b) != 0)
         r = (r + x) % m;
      x = (x + x) % m;
      b *= 2;
      n++;
   }

   return r;
}

tU32 genRand()
{
	tU32 x = (tU32)RtcGetTick();//123456;
	tU32 m = 1 << 31;
	tU32 a = 69069;
	tU32 c = 5;

	//tU32 x = 12345;

   x = (mult(a,x,m) + c) % m;
   return x;
}

void intToChar(tU32 val, char* ret)
{
	char c[100];
	int div;
	int cnt = 0;
	int i;
	tU32 v = val;
	tBool ended = FALSE;

	while(!ended)
	{
		div = v % 10;
		v = v / 10;

		c[cnt] = div + 48;
		cnt++;

		if(v == 0)
		{
			//c[cnt] = '\0';
			break;
		}
	}

	for(i = 0; i <= cnt; i++)
	{
		ret[i] = c[cnt - i - 1];
	}

	ret[i] = '\0';
}

void Sleep(tU32 ms)
{
	T1Start(ms);
	while(T1Stopped());
}
